package com.mkconcepts.firstmate.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class FirstMateServerServlet extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");

		if (APIKeyIsValid(req)) {
			resp.getWriter().println(" Missing or invalid API Key ");
			resp.setStatus(401);
			return;
		}
		;
		String zoneCode = req.getParameter("zone");
		if (forecastIsValid(zoneCode, "coastal")) {
			writeForecast(zoneCode, "coastal", resp);
		} else {
			writeForecast(zoneCode, "offshore", resp);
		}
		
	}

	private boolean forecastIsValid(String zoneCode, String zoneType) {
		URL url;
		HttpURLConnection conn;
		BufferedReader rd;
		String line;
		boolean result = true;
		try {
			url = new URL(buildURL(zoneCode, zoneType));
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			while ((line = rd.readLine()) != null) {
				if (line.contains("does not exist")) {
					result = false;
					break;
				}
			}
			rd.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public void writeForecast(String zoneCode, String zoneType, HttpServletResponse resp) {
		URL url;
		HttpURLConnection conn;
		BufferedReader rd;
		String line;
		try {
			url = new URL(buildURL(zoneCode, zoneType));
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			while ((line = rd.readLine()) != null) {
				resp.getWriter().println(line);
			}
			rd.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String buildURL(String zoneCode, String zoneType) {

		if (zoneCode == null)
			return null;

		String zonePrefix = zoneCode.substring(0, 2);
		String area = (zonePrefix.equalsIgnoreCase("ls") ||
						zonePrefix.equalsIgnoreCase("lh") ||
						zonePrefix.equalsIgnoreCase("lm") ||
						zonePrefix.equalsIgnoreCase("le") ||
						zonePrefix.equalsIgnoreCase("lo") || zonePrefix.equalsIgnoreCase("sl")

		) ? "great_lakes" : zoneType;

		return "http://weather.noaa.gov/cgi-bin/fmtbltn.pl?file=forecasts/marine/" +
				area +
				"/" +
				zonePrefix +
				"/" +
						zoneCode +
				".txt";

	}

	private boolean APIKeyIsValid(HttpServletRequest req) {

		String apiKey = req.getParameter("apiKey");
		// return true;

		return (apiKey == null || !(apiKey.equals("AIzaSyBHbcwY0rNZZwxjIq-ONtrIzyiAPL_yDYM"))) ? false : true;

	}

	@Override
	public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
		resp.addHeader("Access-Control-Allow-Headers", "X-Requested-With, X-PINGOTHER");

	}
}
